package a06_栈与队列;

import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

/**
 * <p>
 * a08_前K个高频元素复习3
 * </p>
 *
 * @author flyduck
 * @since 2025/2/17
 */
public class a08_前K个高频元素复习3 {

    public static void main(String[] args) {
        topKFrequent(new int[]{1,1,1,2,2,3}, 2);
    }

    public static int[] topKFrequent(int[] nums, int k) {
        Map<Integer,Integer> map = new HashMap<>();
        for (int num : nums) {
            if(!map.containsKey(num)){
                map.put(num, 1);
            }else {
                map.put(num, map.get(num) + 1);
            }
        }

        PriorityQueue<int[]> priorityQueue = new PriorityQueue<>((item1,item2) -> item2[1] - item1[1]);
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            priorityQueue.add(new int[]{entry.getKey(),entry.getValue()});
        }

        int[] result = new int[k];
        for (int i = 0; i < k; i++) {
            result[i] = priorityQueue.poll()[0];
        }

        return result;
    }
}
